package middlewares

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"hitme/go-api/modules/logger"
	"hitme/go-api/modules/response"
	"io/ioutil"
	"net"
	"net/http"
	"net/http/httputil"
	"os"
	"strings"
	"time"
)

// GinLogger 接收gin框架默认的日志
func GinLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		// 请求路径
		path := c.Request.URL.Path
		// 请求参数
		//query := c.Request.URL.RawQuery
		query, _ := ioutil.ReadAll(c.Request.Body)

		// 再重新写回请求体body中，ioutil.ReadAll会清空c.Request.Body中的数据
		c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(query))

		c.Next()

		cost := time.Since(start)

		// 记录接口请求日志
		if 200 == c.Writer.Status() {
			logger.Info(path,
				zap.Int("status", c.Writer.Status()),
				zap.String("method", c.Request.Method),
				zap.String("path", path),
				zap.String("query", string(query)),
				zap.String("ip", c.ClientIP()),
				zap.String("user-agent", c.Request.UserAgent()),
				zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
				zap.Duration("cost", cost),
			)
		} else {
			logger.Error(path,
				zap.Int("status", c.Writer.Status()),
				zap.String("method", c.Request.Method),
				zap.String("path", path),
				zap.String("query", string(query)),
				zap.String("ip", c.ClientIP()),
				zap.String("user-agent", c.Request.UserAgent()),
				zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
				zap.Duration("cost", cost),
			)
		}
	}
}

// GinRecovery recover掉项目可能出现的panic，并使用zap记录相关日志
func GinRecovery(stack bool) gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				// Check for a broken connection, as it is not really a
				// condition that warrants a panic stack trace.
				var brokenPipe bool
				if ne, ok := err.(*net.OpError); ok {
					if se, ok := ne.Err.(*os.SyscallError); ok {
						if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
							brokenPipe = true
						}
					}
				}

				httpRequest, _ := httputil.DumpRequest(c.Request, false)
				if brokenPipe {
					logger.Error(c.Request.URL.Path,
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
					// If the connection is dead, we can't write a status to it.
					//c.Error(err.(error)) // nolint: errcheck
					c.Abort()

					response.Err(c, http.StatusInternalServerError, 500, "系统正在开小差，请稍后重新尝试哦~")
					return
				}

				logger.Error(c.Request.URL.Path,
					zap.Any("error", err),
					zap.String("request", string(httpRequest)),
				)

				//c.AbortWithStatus(http.StatusInternalServerError)
				response.Err(c, http.StatusInternalServerError, 500, "系统正在开小差，请稍后重新尝试哦~")
				return
			}
		}()
		c.Next()
	}
}